package com.yijumao.shop.controller;

import com.yijumao.shop.domain.*;
import com.yijumao.shop.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author konley
 * @date 2020-11-15 15:55
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    //生成订单
    @RequestMapping("/create")
    public String create(HttpSession session , Model model){
        //生成订单时用户必须登录
        User user = (User) session.getAttribute("user");
        if(user==null){
            //没有登录的情况
            model.addAttribute("error","请先登录再下单");
            return "redirect:/user/login";
        }
        //从session中取出购物车
        Cart cart = (Cart) session.getAttribute("cart");
        //创建订单对象
        Orders order = new Orders();
        order.setOid(UUID.randomUUID().toString().replace("-",""));//订单编号
        order.setOrdertime(new Date(System.currentTimeMillis()));//下单时间
        order.setTotal(cart.getTotal());//订单金额
        order.setUid(user.getUid());//下单人id
        order.setState(1);//默认未付款
        //创建下单的订单项
        Map<Integer, CartItem> cartItems = cart.getCartItems();
        Set<Map.Entry<Integer, CartItem>> entries = cartItems.entrySet();
        for (Map.Entry<Integer, CartItem> entry : entries) {
            //创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setItemid(UUID.randomUUID().toString().replace("-",""));//订单项id
            orderItem.setCount(entry.getValue().getCount());//购买数量
            orderItem.setId(entry.getValue().getItem().getId());//购买商品的id
            orderItem.setOid(order.getOid());//订单id
            orderItem.setItem(entry.getValue().getItem());//商品对象
            orderItem.setSubtotal(entry.getValue().getSubtotal());//订单小计
            order.getOrderItems().add(orderItem);//向订单添加订单项
        }
        //生成订单
        orderService.creatOrder(order);
        //清空购物车
        session.removeAttribute("cart");
        //发送订单回显
        model.addAttribute("order",order);
        return "order";
    }
}
